﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebInstagram.DAL;
using WebInstagram.Models;

namespace WebInstagram.Controllers
{
    public class PhotoController : Controller
    {
        Context context = new Context();
        PhotosRep photoRep = new PhotosRep();
        CommentsRepository commRep = new CommentsRepository();
        LikesRepository likesRep = new LikesRepository();

        [Authorize]
        // GET: Photo
        public ActionResult Details(int ID)
        {
            var photo = photoRep.GetById(ID);

            if (photo == null)
                return RedirectToAction("Index","Home");

            ViewBag.LoggedUser = User.Identity.Name;
            ViewBag.UserName = photo.User;

            return View(photo);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Details(int ID, string commentText)
        {
            var photo = photoRep.GetById(ID);
            if (photo == null)
                return RedirectToAction("Index", "Home");

            if (string.IsNullOrWhiteSpace(commentText))
                return View(photo);

            Comment comment = new Comment();
            comment.Text = commentText;
            comment.User = User.Identity.Name;
            comment.PhotoID = ID;

            commRep.Insert(comment);


            ViewBag.LoggedUser = User.Identity.Name;
            ViewBag.UserName = photo.User;

            return RedirectToAction("Details", ID);
        }

        [Authorize]
        public ActionResult Delete(int photoID)
        {
            var item = photoRep.GetById(photoID);

            if (item != null)
                if (item.User == User.Identity.Name)
                    photoRep.Delete(item);

            return RedirectToAction("Index","Home");
        }

        [Authorize]
        public ActionResult Like(int photoID)
        {
            var like = context.Likes.Where(l => l.User == User.Identity.Name && l.PhotoID == photoID).FirstOrDefault();
                
            if (like == null)
            {
                context.Likes.Add(new Like() { PhotoID = photoID, User = User.Identity.Name });
            }
            else
            {
                context.Likes.Remove(like);
            }

            context.SaveChanges();

            var photo = context.Photos.Where(p => p.Id == photoID).FirstOrDefault();


            return RedirectToAction("Details", photo);
        }


        [Authorize]
        public ActionResult DeleteComment(int commentID)
        {
            var item = commRep.GetById(commentID);
            var ID = item.PhotoID;

            if (item != null)
                if (item.User == User.Identity.Name)
                    commRep.Delete(item);

            return RedirectToAction("Details", new { ID = ID });
        }



    }
}